<template>
  <div
    style='position: relative'
    :style='{ backgroundColor: layoutaction.color }'
  >
    <n-layout
      has-sider
      class='w-screen h-screen min-w-1000px z-1 bg-blue-400 bg-opacity-0'
    >
      <n-layout-sider
        bordered
        collapse-mode='width'
        :collapsed-width='64'
        :width='200'
        :collapsed='collapsed'
        show-trigger='bar'
        class='bg-blue-400 bg-opacity-0'
        @collapse='editzhankai(true)'
        @expand='editzhankai(false)'
      >
        <n-menu
          :collapsed='collapsed'
          :collapsed-width='64'
          :collapsed-icon-size='22'
          :options='menuOptions'
          :indent='12'
          :render-label='renderMenuLabel'
          :render-icon='renderMenuIcon'
          :expand-icon='expandIcon'
          :on-update:value='tiaozhuan'
          class='bg-blue-400 bg-opacity-0'
        />
      </n-layout-sider>
      <n-layout class='bg-blue-400 bg-opacity-0'>
        <n-layout-header bordered class='bg-blue-400 bg-opacity-0'>
          <myheader />
        </n-layout-header>
        <n-layout-content class='pl-20px relative'>
          <div  class='absolute top-0 left-0 right-0 h-8 overflow-hidden border-b border-gray-400 '>
            <Draggable
              id='huadongref' :list='routelist' item-key='name' :animation='100'
                       :sort='true' class='h-full w-full flex overflow-hidden items-center' @end='end1'>
              <template #item='{ element }'>
                <div 
                     :ref='(el)=>getref(el,element.name)'
                     class='h-full w-200px juzhong1 flex-shrink-0 border cursor-pointer hover:border-red-500'
                     :class="[tabname.toString()===element.name.toString()?'border-blue-300':'']" @click.stop='changeactive(element.name)' @contextmenu='(e)=>handleContextMenu(e,element)'>
                  <div class='flex-1 h-full juzhong1 hover:text-red-500' :class="[tabname.toString()===element.name.toString()?'text-blue-300':'']">
                    <span>{{ element.name }}</span>
                  </div>
                  <div 
                      class='w-20px h-full juzhong1 hover:text-red-500 cursor-pointer select-none'
                      @click.stop='deleteActiveName(element.name)'>
                   <n-icon size='16'>
                     <CloseCircleTwotone></CloseCircleTwotone>
                   </n-icon>
                  </div>
                </div>
              </template>
            </Draggable>
          </div>
          <div class='absolute top-8 left-20px right-0 bottom-0 bg-gray-400'>
            <router-view v-slot='{ Component }'>
              <transition>
                <keep-alive :include='menuNameList'>
                  <component :is='Component' @vnode-mounted="huadongbiaoqian" />
                </keep-alive>
              </transition>
            </router-view>
          </div>
        </n-layout-content>
      </n-layout>
      <div
        class='fixed inset-0 bg-gray-600 juzhong1 z-999'
        v-if='layoutaction.lockscreen'
      >
        <div class='w-600px h-600px juzhong1 flex-col' v-if='startunlock'>
          <div>
            <n-avatar
              :size='100'
              :src='useraction.touxiang || touxiang'
              class='my-1'
            />
          </div>
          <div class='my-1'>{{ useraction.name }}</div>
          <div class='my-1'>
            <n-input v-model:value='password' type='password'></n-input>
          </div>
          <div class='my-1'>
            <n-button class='text-blue-500' @click='fannhui()'>返回</n-button>
            <n-button class='text-blue-500 mx-3' @click='gotologin'
            >重新登录
            </n-button
            >
            <n-button class='text-blue-500' @click='opensystem'
            >进入系统
            </n-button
            >
          </div>
        </div>
        <div
          v-else
          class='w-full h-full flex flex-col justify-center items-center'
        >
          <div class='juzhong1 flex-col'>
            <span class='text-white text-8xl'>{{
                shijian.toLocaleString('zh', {
                  hour12: false,
                  hour: 'numeric',
                  minute: 'numeric',
                  second: 'numeric',
                })
              }}</span>
            <span class='text-white text-3xl'>{{
                shijian.toLocaleString('zh', {
                  year: 'numeric',
                  month: 'numeric',
                  day: 'numeric',
                  weekday: 'long',
                })
              }}</span>
          </div>
          <div>
            <n-icon size='100' @click='kaishijiesuo'>
              <UnlockOutlined></UnlockOutlined>
            </n-icon>
          </div>
          <div class='text-3xl'>天气模块</div>
        </div>
      </div>
    </n-layout>
    <!--    背景颜色-->
    <div
      v-if="layoutaction.bgtype === 'color'"
      class='absolute inset-0 -z-1'
      :style='{ backgroundColor: layoutaction.color }'
    ></div>
    <!--    背景图片-->
    <div
      v-if="layoutaction.bgtype === 'bgimg'"
      class='absolute inset-0 bg-center bg-scroll bg-cover'
      :style='{ backgroundImage: `url(${layoutaction.bgimg})` }'
    ></div>
    <!--    全局遮罩层-->
    <div
      v-show='zhezhaoceng'
      class='
        absolute
        inset-0
        z-20000
        bg-gray-500 bg-opacity-50
        juzhong1
        flex-col
      '
    >
      <myloadicon class='!w-50px !h-50px'></myloadicon>
      <span class='select-none text-blue-400'>正在加载</span>
    </div>
    <n-dropdown
      placement='bottom-start'
      trigger='manual'
      :x='x'
      :y='y'
      :options='options'
      :show='showDropdown'
      :on-clickoutside='onClickoutside'
      @select='handleSelect'
    />
    <n-watermark
      :content='shuiyin'
      selectable
      :font-size='16'
      :line-height='16'
      :width='192'
      :height='128'
      :x-offset='12'
      :y-offset='80'
      :rotate='-15'
      fullscreen
    ></n-watermark>
  </div>
</template>

<script setup name='MainHtml' lang='ts'>
import Draggable from 'vuedraggable'
import { useRouter } from 'vue-router'
import myheader from './myheader.vue'
import { useLayout } from '../../store/moduls/layout'
import { NIcon, useMessage, useDialog, NImage } from 'naive-ui'
import { ChevronDownOutline } from '@vicons/ionicons5'
import { UnlockOutlined, CloseCircleOutlined,CloseCircleTwotone } from '@vicons/antd'
import { Book, BookOpen } from '@vicons/fa'
import usetime from '../../hooks/mytime'
import { useUserInfo } from '../../store/moduls/userinfo'
import http from '@/request/request'
import { computed, h, nextTick, watch, onMounted, provide, ref, Ref } from 'vue'
import { useMneu } from '../../store/moduls/menu'
import { useMyRouter } from '../../store/moduls/usemyroute'
import { storeToRefs } from 'pinia' // 将pinia的属性变成响应式
const router = useRouter()

const shijian = usetime()
const dialog = useDialog()
const layoutaction = useLayout()
const useraction = useUserInfo()
const mymenu = useMneu()
const myRouter = useMyRouter()
const message = useMessage()

const { zhezhaoceng } = storeToRefs(layoutaction)
const { name, username, id } = storeToRefs(useraction)
const { activeName: tabname, routelist } = storeToRefs(myRouter)

/*********************************************************************************
 全局的水印文字
 *********************************************************************************/

const shuiyin = computed(() => {
  return name.value ? '阅读者    --    ' + name.value : '--游客阅览--'
})
/*********************************************************************************
 被缓存的路由列表
 *********************************************************************************/
const menuNameList = computed(() => {
  console.log("routelist变了一次**********************************************************")
  return routelist.value.map((item: any) => {
    return item.name
  })
})

/*********************************************************************************
 顶部tab栏的渲染和控制
 *********************************************************************************/

// 点击顶部的tab导航
const changeactive = (name: string) => {
  console.log('点击标签', name)
  router.push({ name: name })
}
// 删除顶部tab导航
const deleteActiveName = (name: string) => {
  myRouter.yichu([name])
}

/*********************************************************************************
 锁屏页面的控制
 *********************************************************************************/

// 默认的头像
const touxiang: Ref = ref('http://101.43.194.47:9000/file/yuangong.webp')
// 解锁的密码
const password: Ref = ref('')

const collapsed = computed(() => layoutaction.zhankai)
const editzhankai = (jieguo: boolean) => {
  layoutaction.changezhankai(jieguo)
}
// 解锁
const jiesuo = () => {
  layoutaction.changelock(false)
}
// 开始解锁
const startunlock = ref(false)
const daojishi = ref(0)
const kaishijiesuo = () => {
  startunlock.value = true
  daojishi.value = 30
  setTimeout(xunhuan1, 1000)
}
const xunhuan1 = () => {
  daojishi.value = daojishi.value - 1
  // 如果已经解锁就停止循环
  if (!layoutaction.lockscreen) {
    daojishi.value = 0
    startunlock.value = false
  } else if (daojishi.value <= 0) {
    // 如果时间到了，就回到锁屏界面
    fannhui()
  } else {
    //  如果时间没到就继续计时
    setTimeout(xunhuan1, 1000)
  }
}
// 点击返回
const fannhui = () => {
  daojishi.value = -1
  startunlock.value = false
  password.value = ''
}
// 点击重新登录
const gotologin = () => {
  useraction.zhuxiao()
  router.replace({ name: 'Login' })
}

// 点击进入系统
const opensystem = () => {
  http
    .login({ username: username.value, password: password.value })
    .then(({ data }) => {
      if (data.code === 0) {
        message.success('验证成功')
        jiesuo()
      } else {
        data.error
          ? Object.values(data.error).forEach((item: any) => {
            message.error(item)
          })
          : message.error(data.msg || '登录失败')
      }
    })
    .catch((err: any) => {
      message.error(err)
    })
}
/*********************************************************************************
 左侧菜单的渲染
 *********************************************************************************/
const menuOptions = computed(() => {
  const shuzu = mymenu.menulist.find((el) => el.key === mymenu.firstmenu)
  console.log(shuzu, '找到的数据')
  return shuzu ? shuzu.children : []
})

// 渲染完整文字
const renderMenuLabel = (option: any) => {
  return h('span', null, {
    default: () => {
      return option.label
    },
  })
}
// 只渲染图标
const renderMenuIcon = (option: any) => {
  return h(NIcon, null, { default: () => h(collapsed.value ? Book : BookOpen) })
}
// 不渲染
const expandIcon = (option: any) => {
  return h(NIcon, null, { default: () => h(ChevronDownOutline) })
}
// 点击菜单跳转
const tiaozhuan = (key: string, item: any) => {
  router.push({ name: key })
}

/*********************************************************************************
 创建一个注册函数，将所有子组件的初始化方法注册到顶部
 *********************************************************************************/
interface shuaxinfunctype {
  [propname: string]: Function
}

const shuaxinfunclist = ref<shuaxinfunctype>({})

const zhuceshuaxinfunc = (shuaxinfangfa: shuaxinfunctype) => {
  console.log('收到一个注册请求')
  shuaxinfunclist.value = { ...shuaxinfunclist.value, ...shuaxinfangfa }
}
provide('zhuceshuaxinfunc', zhuceshuaxinfunc)
/*********************************************************************************
 顶部tab的右键菜单
 *********************************************************************************/
// 关闭顶部tabs
const handleClose = (name: string) => {
  myRouter.yichu([name])
}
const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const options = ref([
  { label: '刷新', key: 'refresh' },
  { label: '关闭', key: 'close' },
  { label: '关闭左侧', key: 'closeleft' },
  { label: '关闭右侧', key: 'closeright' },
  { label: '关闭其他', key: 'closeother' },
  { label: '全部关闭', key: 'closeall' },
])
const selecttab = ref<{ name: string } | null>(null)
const handleSelect = (key: string) => {
  let panduan: boolean
  const namelist: Array<string> = []
  switch (key) {
    case 'close': // 关闭选中的
      myRouter.yichu([selecttab.value!.name])
      break
    case 'refresh': // 刷新选中的
      const shuaxinfunc = shuaxinfunclist.value[selecttab.value!.name]
      shuaxinfunc && shuaxinfunc()
      break
    case 'closeleft': // 关闭左侧
      panduan = true
      routelist.value.forEach((item: any) => {
        if (item.name === selecttab.value!.name) {
          panduan = false
        } else if (panduan) {
          namelist.push(item.name)
        }
      })
      myRouter.yichu(namelist)
      break
    case 'closeright': // 关闭右侧
      panduan = false
      routelist.value.forEach((item: any) => {
        if (item.name === selecttab.value!.name) {
          panduan = true
        } else if (panduan) {
          namelist.push(item.name)
        }
      })
      console.log(routelist.value, '删除前的列表')
      console.log(namelist, '待删除的name')
      myRouter.yichu(namelist)
      break
    case 'closeother': // 关闭其他
      for (let i = 0; i < routelist.value.length; i++) {
        if (routelist.value[i].name !== selecttab.value!.name) {
          namelist.push(routelist.value[i].name)
        }
      }
      myRouter.yichu(namelist)
      break
    case 'closeall': // 关闭其他
      myRouter.qingkong()
      break
  }
  onClickoutside()
}
const onClickoutside = () => {
  showDropdown.value = false
}
const handleContextMenu = (e: MouseEvent, tab: any) => {
  console.log('右键点击')
  selecttab.value = tab
  e.preventDefault()
  showDropdown.value = false
  nextTick().then(() => {
    showDropdown.value = true
    x.value = e.clientX
    y.value = e.clientY
  })
}

/*********************************************************************************
 一个删除的弹窗，使用注入，给所有的子组件使用
 *********************************************************************************/
const delDialog = (
  shaxinfunc: Function,
  delfunc: Function,
  itemid: string | number,
  itemname:string|null = null,
) => {
  const init = () => {
    const cc = dialog.error({
      title: '枪毙',
      content: () => {
        return h(
          'div',
          { class: { 'w-400px h-40px flex items-center': true } },
          [
            '我为党国立过功，我为委座流过血，你们不能杀我！',
            h(
              NImage,
              {
                src: 'https:////lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/jj_emoji_6.dde0d83.png',
                height: 40,
                width: 40,
                previewDisabled: true,
              },
              {
                default() {
                },
              },
            ),
            // return itemname ? `确认删除${itemname}？` : '我为党国立过功，我为委座流过血，你们不能杀我！'
          ],
        )
      },
      positiveText: '必须枪毙',
      negativeText: '放了吧',
      showIcon: false,
      onPositiveClick: () => {
        cc.loading = true
        delfunc(null, itemid)
          .then((res: any) => {
            if (res && res.data.code === 0) {
              getsuccess()
            } else {
              getfaild(res.data.error.toString())
            }
          })
          .catch((err: any) => {
            getfaild(err)
          })
      },
    })
  }
  const getsuccess = () => {
    const aa = dialog.success({
      title: '删除成功',
      content: () => {
        return h(
          'span',
          {},
          {
            default() {
              return '删除数据成功！'
            },
          },
        )
      },
      negativeText: '关闭',
      showIcon: false,
    })
    setTimeout(() => {
      shaxinfunc()
      aa.destroy()
    }, 1000)
  }
  const getfaild = (errortext: any) => {
    dialog.error({
      title: '删除失败',
      content: () => {
        return h(
          'span',
          {},
          {
            default() {
              return errortext || '删除错误'
            },
          },
        )
      },
      negativeText: '关闭',
      showIcon: false,
    })
  }
  init()
}

// 依赖注入区域
provide('delDialog', delDialog) // provide的第一个为名称，第二个值为所需要传的参数

/*********************************************************************************
 挂载完成生命周期，顶部tab栏的左右滑动监听
 *********************************************************************************/
onMounted(() => {
  const huadongref: HTMLElement | null = document.getElementById('huadongref')
  //判断浏览器
  let isIE: any = navigator.userAgent.match(/MSIE (\d)/i)
  isIE = isIE ? isIE[1] : undefined
  let isFF = /FireFox/i.test(navigator.userAgent)

  if (isIE < 9)
    //传统浏览器使用MouseWheel事件
    huadongref?.attachEvent('onmousewheel', function(e: any) {
      console.log('IE9一下的浏览器触发滚动')
      //计算鼠标滚轮滚动的距离
      //一格3行，每行40像素
      let v = e.wheelDelta / 2
      huadongref.scrollLeft += v
      //阻止浏览器默认方法
      return false
    })
  else if (!isFF)
    //除火狐外的现代浏览器也使用MouseWheel事件
    huadongref?.addEventListener(
      'mousewheel',
      function(e: any) {
        console.log('除火狐以外的浏览器触发滚动')
        //计算鼠标滚轮滚动的距离
        let v = -e.wheelDelta / 2
        huadongref.scrollLeft += v
        //阻止浏览器默认方法
        e.preventDefault()
      },
      false,
    )
  //火狐使用DOMMouseScroll事件
  else
    huadongref?.addEventListener(
      'DOMMouseScroll',
      function(e: any) {
        console.log('火狐浏览器触发滚动')
        //计算鼠标滚轮滚动的距离
        //一格是3行，但是要注意，这里和像素不同的是它是负值
        huadongref.scrollLeft += e.detail * 20
        //阻止浏览器默认方法
        e.preventDefault()
      },
      false,
    )
})
// 初始化函数
const init = () => {
  if (!id.value) {
    router.push({ name: 'Login' })
  }
}
// 存放顶部标签组件的对象
const tagsobj = ref({})
const getref = (el: any, name: string) => {
  // 不用判断，将最新的数据放进去
  console.log(el, name, '注册组件的参数都是什么')
  tagsobj.value[name] = el
}
// 滑动标签栏让当前激活的标签漏出来
const huadongbiaoqian=()=>{
  console.log("*************************************当前组件挂载完成，滑动试试**********************************************")
  const zujian = tagsobj.value[tabname.value]
  console.log(zujian,"找到的组件是什么啊")
  const offleft = zujian.offsetLeft
  const huadongref: HTMLElement | null = document.getElementById('huadongref')
  if (offleft > (huadongref.scrollLeft + huadongref.offsetWidth)) {
    huadongref.scrollLeft = offleft + 200
  } else if (huadongref.scrollLeft > offleft) {
    huadongref.scrollLeft = offleft
  }
}

// 阻止火狐浏览器的拖拽导致打开百度搜索的bug
const end1 = () => {
  document.body.ondrop = (event:any) => {
    event.preventDefault();
    event.stopPropagation();
  }
}
/*********************************************************************************
 初始化区域
 *********************************************************************************/
init()
</script>

